import React, { useState, useEffect } from 'react';
import OpenAIClient from '@/lib/llm';
import ReactMarkdown from 'react-markdown';
import rehypeHighlight from 'rehype-highlight';
import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/textarea';
import { Card, CardHeader, CardTitle, CardContent, CardFooter } from '@/components/ui/card';
import { Copy, RefreshCw, Sparkles } from 'lucide-react';

const PromptGenerator = () => {
  const [input, setInput] = useState('');
  const [output, setOutput] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  const generatePrompt = async () => {
    if (!input.trim()) {
      setError('请输入需求描述');
      return;
    }

    setLoading(true);
    setError(null);
    
    try {
      const client = new OpenAIClient();
      const messages = [
        {
          role: 'system',
          content: '你是一位专业的Prompt工程师，擅长根据用户需求生成详细、结构化的Prompt。直接生成Prompt，不要解释。prompt生成到```markdown  ```中'
        },
        {
          role: 'user',
          content: `请根据以下需求生成一个专业Prompt：
需求描述：${input}

要求：
1. 生成Markdown格式的Prompt
2. 包含具体场景描述
3. 包含期望的输出格式和示例
4. 语言：中文
5. 风格：专业且友好
6. 长度：300-500字
7. 主要由角色，功能，约束，输出格式，示例组成。
`
        }
      ];

      const response = await client.chat(messages, {
        temperature: 0.7,
        max_tokens: 1000
      });
      setOutput(response);
    } catch (err) {
      console.error('生成Prompt失败:', err);
      setError('生成Prompt失败，请稍后重试');
    } finally {
      setLoading(false);
    }
  };

  const copyToClipboard = () => {
    navigator.clipboard.writeText(output);
  };

  return (
    <Card className="h-full flex flex-col">
      <CardHeader className="pb-3">
        <div className="flex items-center gap-3">
          <Sparkles className="text-purple-500" size={24} />
          <CardTitle>Prompt生成器</CardTitle>
        </div>
      </CardHeader>
      <CardContent className="flex-1 grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* 左侧输入区域 */}
        <div className="space-y-4">
          <div>
            <label className="block mb-2 text-sm font-medium">输入需求描述</label>
            <Textarea
              value={input}
              onChange={(e) => setInput(e.target.value)}
              placeholder="例如：生成一个用于AI绘画的详细Prompt"
              className="min-h-[200px]"
            />
          </div>
          
          <div className="bg-gray-50 p-4 rounded-lg">
            <h3 className="text-sm font-medium mb-2">提示技巧</h3>
            <ul className="text-xs text-gray-600 space-y-1 list-disc pl-5">
              <li>明确说明任务类型（写作、绘画、编程等）</li>
              <li>指定期望的输出格式和风格</li>
              <li>提供具体场景和背景信息</li>
              <li>添加约束条件（长度、语言等）</li>
            </ul>
          </div>
        </div>
        
        {/* 右侧输出区域 */}
                  <div className="flex flex-col">
                    <label className="block mb-2 text-sm font-medium">生成的Prompt</label>
                    <div className="relative flex-1">
                      {loading && <div className="absolute inset-0 flex items-center justify-center bg-gray-50/50">生成中...</div>}
                      {error && <div className="text-red-500 mb-2">{error}</div>}
                      <div className="bg-gray-50 rounded-md p-4 font-mono text-sm overflow-auto h-full min-h-[300px]">
                        {output ? (
                          <div className="prose prose-zinc max-w-none dark:prose-invert">
                            <ReactMarkdown rehypePlugins={[rehypeHighlight]}>
                              {output}
                            </ReactMarkdown>
                          </div>
                        ) : (
                          <div className="text-gray-500">
                            生成的Prompt将显示在这里
                          </div>
                        )}
                      </div>
                      {output && !loading && (
                        <Button 
                          size="icon" 
                          variant="ghost" 
                          className="absolute top-2 right-2"
                          onClick={copyToClipboard}
                        >
                          <Copy size={16} />
                        </Button>
                      )}
                    </div>
                  </div>
      </CardContent>
      <CardFooter>
        <Button 
          onClick={generatePrompt} 
          className="w-full bg-purple-600 hover:bg-purple-700"
          disabled={loading}
        >
          {loading ? (
            <>加载中...</>
          ) : (
            <> <RefreshCw className="mr-2" size={16} /> 生成Prompt </>
          )}
        </Button>
      </CardFooter>
    </Card>
  );
};

export default PromptGenerator;